/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2025. All rights reserved.
 *
 */
import fs from 'fs';
import path from 'path';

import { taskCenter } from '../plugins/task-builder/test-task-center';

const filename = 'failedCases.txt';
const targetFilePath = path.join(__dirname, filename);
if (fs.existsSync(targetFilePath)){
  const failedCases = fs.readFileSync(targetFilePath, 'utf-8').split('\n');
  if (failedCases.length > 0 && !failedCases.includes('')){
    describe('Failed case test again', () => {
      fs.rmSync(targetFilePath);

      taskCenter.runTask({
        caseName: failedCases
      }).then(finalFailedCases => {
        if (finalFailedCases.length > 0) {
          console.log(`Finally failed ${finalFailedCases.length} test lists ${finalFailedCases.map(c => `${c.caseName}, `)}`);
          throw new Error(`Finally failed tests: \n ${finalFailedCases.map(c => `${c.caseName},reason:${c.error}\n`)}`);
        } else {
          console.log('Test Passed');
        }
      });
    });
  } else {
    describe('No failed cases', () => {
      fs.rmSync(targetFilePath);
      it('should pass', () => {
        // empty test, in case test suite failed for no tests detected
      });
    });
    console.log('No failed cases. Test passed.');
  }
} else {
  throw new Error('No failedCases.txt found');
}